﻿//using FlyingEye.Exceptions;
//using Microsoft.AspNetCore.Diagnostics;
//using Microsoft.AspNetCore.Mvc;
//using System.Diagnostics;
//using System.Security.Principal;

//namespace FlyingEye.Extensions
//{
//    public class GlobalExceptionHandler : IExceptionHandler
//    {
//        private readonly ILogger _logger;

//        public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) => _logger = logger;

//        public async ValueTask<bool> TryHandleAsync(
//            HttpContext httpContext,
//            Exception ex,
//            CancellationToken cancellationToken)
//        {
//            // 1. 获取增强版追踪标识
//            var traceId = Activity.Current?.TraceId.ToString() ?? httpContext.TraceIdentifier;
//            var spanId = Activity.Current?.SpanId.ToString() ?? "00";
//            var flags = Activity.Current?.ActivityTraceFlags != ActivityTraceFlags.None ? "01" : "00";
//            var userId = httpContext.User.FindUserId()?.ToString() ?? "Anonymous";

//            // 2. 统一日志模板（网页2/5）
//            var logTemplate = "TraceId:00-{TraceId}-{SpanId}-{Flag} | Path:{Path} | Method:{Method} | User:{UserId}";

//            if (ex is BusinessException)
//            {
//                _logger.LogInformation(ex, logTemplate,
//                    traceId, spanId, flags,
//                    httpContext.Request.Path, httpContext.Request.Method, userId);

//                // 3. 构建增强版错误响应（网页4/8）
//                var statusCode = GetStatusCode(ex);
//                var problemDetails = new ProblemDetails
//                {
//                    Title = "API Operation Failed",
//                    Instance = httpContext.Request.Path,
//                    Detail = ex is BusinessException ? ex.Message : "Request failed, check TraceId for details",
//                    Status = statusCode,
//                    Type = $"https://api.flyingeye.com/errors#{ex.GetType().Name}",
//                    Extensions =
//                {
//                    ["traceId"] = traceId,
//                }
//                };

//                // 4. 支持多种 Content-Type（网页5）
//                httpContext.Response.ContentType = "application/problem+json";
//                httpContext.Response.StatusCode = statusCode;
//                await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
//                return true;
//            }
//            else
//            {
//                _logger.LogError(ex, logTemplate,
//                    traceId, spanId, flags,
//                    httpContext.Request.Path, httpContext.Request.Method, userId);
//                return false;
//            }
           
//        }

//        private int GetStatusCode(Exception ex)
//        {
//            return ex switch
//            {
//                BusinessOperationException => StatusCodes.Status400BadRequest,
//                ResourceNotFoundException => StatusCodes.Status404NotFound,
//                _ => StatusCodes.Status500InternalServerError
//            };
//        }
//    }
//}
